package com.mfs.manager.log.advice;

import com.alibaba.fastjson2.JSON;
import com.mfs.common.enums.ResponseCodeEnum;
import com.mfs.common.response.BaseResponse;
import com.mfs.common.response.ResponseUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;

/**
 * service 层日志切面
 * */
@Aspect
@Configuration
public class LogAdvice {
    private static final Logger logger = LoggerFactory.getLogger(LogAdvice.class);

    @Pointcut("@annotation(com.mfs.manager.log.Log)")
    public void pointCut(){}

    @Around(value = "pointCut()")
    public Object logAround(ProceedingJoinPoint proceedingJoinPoint) {
        String methodName = proceedingJoinPoint.getSignature().getName();
        String className = proceedingJoinPoint.getTarget().getClass().getName();
        Object[] args = proceedingJoinPoint.getArgs();
        logger.info("正在调用{}.{}方法，入参：{}", className, methodName, JSON.toJSONString(args));
        long begin = System.currentTimeMillis();
        try {
            Object proceed = proceedingJoinPoint.proceed();
            long end = System.currentTimeMillis();
            logger.info("调用{}.{}方法完成，出参：{}，耗时：{}毫秒", className, methodName, JSON.toJSONString(proceed), end - begin);
            return proceed;
        } catch (Throwable throwable) {
            logger.error("调用{}方法失败", methodName, throwable);
            return createInvokeFailedResponse();
        }
    }

    private BaseResponse createInvokeFailedResponse() {
        return ResponseUtil.createResponse(ResponseCodeEnum.ERROR, "调用失败", BaseResponse.class);
    }
}
